import configparser
import utils
import os
import json
import requests
AJAX_Header = {'X-Requested-With': 'XMLHttpRequest'}
from urllib3.exceptions import InsecureRequestWarning
# 禁用安全请求警告
requests.urllib3.disable_warnings(InsecureRequestWarning)

class OneClickLogin:

    def __init__(self, config_file, captcha_file, cookie_file):
        self.config_file = config_file
        self.captcha_file = captcha_file
        self.cookie_file = cookie_file
        self.config = configparser.ConfigParser()
        self.config.read(config_file, encoding='utf-8')
        self.data = {}
        self.session = utils.requests_retry_session()
        self.ensure('Url', '网址', 'http://nx.tuwme.com')
        self.ensure('User', '用户')
        self.ensure('Password', '密码')

    def ensure(self, key, prompt, example=None):
        self.data[key] = self.config.get('Login', key, fallback=None)
        if self.data[key] is None:
            self.data[key] = input("请输入一键登录{}：".format(prompt) if example is None else "请输入一键登录{}（如{}）："
                                   .format(prompt, example))
        else:
            print("使用保存的登录系统{}: {}".format(
                prompt, '****' if key == 'Password' else self.data[key]))

    def get_url(self):
        return self.data['Url']

    def get_username(self):
        return self.data['User']

    def get_password(self):
        return self.data['Password']

    def resume_session(self):
        try:
            if os.path.isfile(self.cookie_file):
                print('存在本地会话缓存，开始测试')
                utils.set_cookies(self.session, json.load(
                    open(self.cookie_file, 'r')))
                test = self.session.get(self.get_url() + '/smaccount/lists?offset=0&pageSize=1&order=asc&wechatname=',
                                        headers=AJAX_Header, verify = False)
                if test.status_code == 200:
                    json_response = test.json()
                    if 'code' in json_response:
                        return json_response['code'] != 1005
                    else:
                        return 'rows' in json_response
                else:
                    return False
            else:
                print('无本地会话缓存')
                return False
        except ValueError:
            os.remove(self.cookie_file)
            return False

    def get_wx_cookie(self, gh_id):
        resp_sign = self.session.get(
            '{}/smaccount/lists?wechatname={}'.format(self.get_url(), gh_id), headers=AJAX_Header, verify = False)
        json_sign = resp_sign.json()
        if json_sign['total'] == 1:
            self.session.cookies.set('sign', json_sign['rows'][0]['sign'])
        resp = self.session.get('{}/api/dogetsession/ghid/{}'.format(self.get_url(), gh_id), headers=AJAX_Header, verify = False)
        try:
            json_resp = resp.json()
            if json_resp['code'] == 1:
                return json_resp['cookie']
            else:
                print('{} 一键登录状态异常: {}'.format(gh_id, json_resp['code']))
                return None
        except ValueError:
            print('获取Cookie错误')
            print(resp.content)
            return None

    def login(self):
        try:
            print('开始登录回话')
            self.session.get(self.get_url() + '/login', verify = False)
            return self.verify()
        except ConnectionError:
            print('启动登录失败')

    def verify(self):
        print('下载验证码')
        captcha = self.session.get(self.get_url() + '/yzm/load', verify = False)
        with open(self.captcha_file, 'wb') as f:
            f.write(captcha.content)
        utils.show_image(self.captcha_file)
        code = input('> 请输入验证码(可手动打开{}查看)：'.format(self.captcha_file))
        data = {'uname': self.get_username(), 'upassword': self.get_password(),
                'yzm': code, 'ref': '/'}
        try:
            response = self.session.post(self.get_url() + '/passport', data=data, headers={
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Encoding': 'gzip, deflate',
                'Referer': self.get_url() + '/loginout',
                'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0'}, verify = False)
            print(response.json()['msg'])
            code = response.json()['code']
            if code == '1001':
                os.remove(self.captcha_file)
                json.dump(self.session.cookies.get_dict(),
                          open(self.cookie_file, 'w'))
                return True
            elif code == '1002':
                print('请重新输入验证码')
                return self.verify()
            elif code == '1003':
                self.data['Username'] = input('> 请重新输入用户名: ')
                self.data['Password'] = input('> 请重新输入密码: ')
                return self.verify()
            elif code == '1004':
                self.data['Password'] = input('> 请重新输入密码: ')
                return self.verify()
            else:
                print(response.json())
        except ConnectionError:
            print('请检查网络')
            return self.verify()


def use_default_login():
    srv = OneClickLogin('config.ini', 'captcha.jpg', 'cookie.json')
    if srv.resume_session():
        print('回话有效，可进行下一步')
    else:
        print('回话失效，重新登录')
        srv.login()
    return srv


if __name__ == '__main__':
    use_default_login()
